﻿using Aop.Api.Request;
using Aop.Api.Response;
using Entity;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace ServiceCore.Tool.AliFace
{
    public interface IFacePay
    {
        ResultObjModel Initialize(string str);

        ResultObjModel StartPay(FacePayParams Params, string Pay_fee, Func<string, ResultObjModel, ResultObjModel> DoSomething);

        ResultTModel<AntMerchantExpandAutomatApplyUploadResponse> Mch_Settlement(sub_mch_settlement Indata);

        List<area_code> get_area { get; }

        ResultObjModel AlipayTradeQueryRequest(string out_trade_no,string trade_no);
    }
    public class FacePay: IFacePay
    {
        private readonly IConfiguration _config;
        public FacePay(IConfiguration Config)
        {
            _config = Config;
        }
        /// <summary>
        /// 支付宝APPID
        /// </summary>
        private string appId { get { return _config["Ali:appId"].ToString(); } }
        /// <summary>
        /// 支付宝APP key
        /// </summary>
        private string appKey { get { return _config["Ali:appKey"].ToString(); } }
        /// <summary>
        /// 支付宝APP 公钥
        /// </summary>
        private string alipay_public_key { get { return _config["Ali:alipay_public_key"].ToString(); } }
        /// <summary>
        /// 天津睿科PID
        /// </summary>
        private string rk_pid { get { return _config["Ali:rk_pid"].ToString(); } }
        /// <summary>
        /// 初始化刷脸支付
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public ResultObjModel Initialize(string str)
        {
            ResultObjModel result = new ResultObjModel(); 
            try
            { 
                if (string.IsNullOrEmpty(str))
                { 
                    result.code = 1;
                    result.msg = "参数不能为空";
                    return result;
                } 
                Aop.Api.DefaultAopClient alipayClient = new Aop.Api.DefaultAopClient("https://openapi.alipay.com/gateway.do",
                   appId, appKey, "json", "1.0", "RSA2", alipay_public_key, "utf-8");
                //创建API对应的request类
                ZolozAuthenticationCustomerSmilepayInitializeRequest request = new ZolozAuthenticationCustomerSmilepayInitializeRequest();
                Zimmetainfo zimmetainfo = null;
                try
                { 
                    zimmetainfo = Newtonsoft.Json.JsonConvert.DeserializeObject<Zimmetainfo>(str); //客户端zolozGetMetaInfo接口返回的metainfo对象 
                }
                catch (Exception ex)
                {
                    //  log.Error("安卓端请求时间：" + DateTime.Now.Tostring(), ex);
                    result.code = 1;
                    result.msg = "初始化请求异常=>" + ex.ToString();
                    return result;
                }
                zimmetainfo.brandCode = "RK";
                var merchantInfo = zimmetainfo.merchantInfo; 
                //设置业务参数
                request.BizContent = Newtonsoft.Json.JsonConvert.SerializeObject(zimmetainfo);   
                ZolozAuthenticationCustomerSmilepayInitializeResponse response = alipayClient.Execute(request); 
                string Payresult = response.Result;
                var resultJson = Newtonsoft.Json.JsonConvert.DeserializeObject<ZimIdAndZimInitClientData>(Payresult);
                string zimId = resultJson.zimId;
                string zimInitClientData = resultJson.zimInitClientData;
                var r = new ZimIdAndZimInitClientData() { zimId = zimId, zimInitClientData = zimInitClientData };  
                result.code = 0;
                result.msg = "Success";
                result.data = r;
                return result;
            }
            catch (Exception ex)
            {
                result.code = 1;
                result.msg = "初始化请求异常=>" + ex.ToString();
                return result;
            }
        }
        /// <summary>
        /// 开始进行一次支付
        /// </summary>
        /// <param name="AliPay"></param>
        /// <param name="DoSomething"></param>
        /// <returns></returns>
        public ResultObjModel StartPay(FacePayParams Params, string Pay_fee, Func<string,ResultObjModel, ResultObjModel> DoSomething)
        {
            ResultObjModel result = new ResultObjModel();
            try
            {
                alipayParameter alipayParmater = new alipayParameter();
                alipayParmater.subject = "购物商品";
                Aop.Api.DefaultAopClient alipayClient = new Aop.Api.DefaultAopClient("https://openapi.alipay.com/gateway.do", appId, appKey, "json", "1.0", "RSA2", alipay_public_key, "utf-8");
                AlipayTradePayRequest request = new AlipayTradePayRequest();
                alipayParmater.out_trade_no = Params.order_No;
                alipayParmater.terminal_id = Params.terminal_id;
                alipayParmater.store_id = Params.store_id;
                alipayParmater.total_amount = Pay_fee;
                alipayParmater.auth_code = Params.ftoken;
                alipayParmater.terminal_params = Params.terminal_params;
                request.BizContent = Newtonsoft.Json.JsonConvert.SerializeObject(alipayParmater);
                AlipayTradePayResponse response = alipayClient.Execute(request);
                var r = response.Body;
                result = DoSomething(r, result);
            }
            catch (Exception ex)
            {
                result.code = 1;
                result.msg = "支付异常=>" + ex.Message;
            }
            return result;
        }
        /// <summary>
        /// 订单查询
        /// </summary>
        /// <param name="AliPay"></param>
        /// <param name="DoSomething"></param>
        /// <returns></returns>
        public ResultObjModel AlipayTradeQueryRequest(string out_trade_no, string trade_no)
        {
            ResultObjModel result = new ResultObjModel();
            try
            {
                Aop.Api.DefaultAopClient alipayClient = new Aop.Api.DefaultAopClient("https://openapi.alipay.com/gateway.do", appId, appKey, "json", "1.0", "RSA2", alipay_public_key, "utf-8");
                AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
                var query_params = new
                {
                    out_trade_no,
                    trade_no
                };

                request.BizContent = Newtonsoft.Json.JsonConvert.SerializeObject(query_params);
                AlipayTradeQueryResponse response = alipayClient.Execute(request);
                result.code = 0;
                result.msg = "success";
                result.data = response;
            }
            catch (Exception ex)
            {
                result.code = 1;
                result.msg = "支付异常=>" + ex.Message;
            }
            return result;
        } 
        /// <summary>
        /// 支付宝刷脸机器入驻
        /// </summary>
        /// <returns></returns>
        public ResultTModel<AntMerchantExpandAutomatApplyUploadResponse> Mch_Settlement(sub_mch_settlement Indata)
        {
            return CoreStartDo.ResultAction<ResultTModel<AntMerchantExpandAutomatApplyUploadResponse>>(result =>
            {
                Aop.Api.DefaultAopClient alipayClient = new Aop.Api.DefaultAopClient("https://openapi.alipay.com/gateway.do", appId, appKey, "json", "1.0", "RSA2", alipay_public_key, "utf-8");
                AntMerchantExpandAutomatApplyUploadRequest request = new AntMerchantExpandAutomatApplyUploadRequest();
                Mch_Settlement_params sub_params = new Mch_Settlement_params();
                sub_params.terminal_id = Indata.terminal_id;
                sub_params.product_user_id = rk_pid;
                sub_params.merchant_user_id = rk_pid;
                sub_params.machine_type = "SCANFACE_AUTOMAT";
                sub_params.machine_cooperation_type = "COOPERATION_STOCK";
                sub_params.merchant_user_type = "ALIPAY_MERCHANT";
                sub_params.machine_delivery_date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                sub_params.machine_name = "天津睿科";
                sub_params.delivery_address = Indata.address;
                sub_params.point_position = new point_position_model
                {
                    area_code = Indata.address.area_code,
                    city_code = Indata.address.city_code,
                    province_code = Indata.address.province_code,
                    machine_address = Indata.address.machine_address
                };
                sub_params.scene = Indata.scene;  
                request.BizContent = Newtonsoft.Json.JsonConvert.SerializeObject(sub_params);   
                AntMerchantExpandAutomatApplyUploadResponse response = alipayClient.Execute(request);
                result.code = 0;
                result.msg = "success";
                result.data = response;
                return result;
            });
        }

        private List<area_code> area_list = new List<area_code>();

        public List<area_code> get_area
        {
            get
            {
                if (area_list == null || !area_list.Any())
                {
                    string read_file_content = ReadTemplate();
                    if (string.IsNullOrWhiteSpace(read_file_content))
                    {
                        return new List<area_code>();
                    }
                    else
                    {
                        try
                        {
                            return Newtonsoft.Json.JsonConvert.DeserializeObject<List<area_code>>(read_file_content);
                        }
                        catch {
                            return new List<area_code>();
                        }
                    }
                }
                else
                {
                    return area_list;
                }
            }
        }  
        /// <summary>
        /// 读取文件
        /// </summary>
        /// <param name="TempInfo"></param>
        private string ReadTemplate()
        {
            try
            {
                string basePath = AppContext.BaseDirectory + "/wwwroot/config/";
                string File_Path = basePath + "/2020area.json";
                if (!File.Exists(File_Path))
                {
                    return "";
                }
                using (FileStream fS = new FileStream(File_Path, FileMode.Open, FileAccess.Read))
                {
                    StreamReader sr = new StreamReader(fS, Encoding.UTF8);//设定读写的编码                 
                    sr.BaseStream.Seek(0, SeekOrigin.Begin);
                    return sr.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
